package com.woniuxy.nio.channel.socketchannel;

import com.woniuxy.nio.util.FileUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Optional;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: ServerSocketChannel 管理连接 负责连接的接入 本身不做读写操作
 * <P> Date: 2022/4/3:11:12
 * <P> Description:
 */

public class ServerSocketChannelDemo1 {
    public static void main(String[] args) throws Exception {
        // 端口号设置

        ByteBuffer buffer = ByteBuffer.wrap("ces1ss".getBytes());

        ServerSocketChannel ssc = ServerSocketChannel.open();

        //绑定
        ssc.socket().bind(new InetSocketAddress(FileUtils.PORT));

        //设置非阻塞模式
        ssc.configureBlocking(false);

        //监听是否有新的连接传入
        while (true) {
            System.out.println("waiting... for connections ");

            //TODO 非阻塞 这里不会阻塞等待
            SocketChannel sc = ssc.accept();

            if (sc == null) {
                System.out.println("null");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("connection from" + sc.socket().getRemoteSocketAddress());

                //TODO 把position设为0，limit不变，一般在把数据重写入Buffer前调用
                buffer.rewind(); //指针0 返回一个
                sc.write(buffer);
                sc.close();
            }

        }

    }
}
